<?php
/**
 * Created by PhpStorm.
 * User: mateng马腾
 * Date: 2018/8/8
 * Time: 下午2:19
 *
 * swoole服务端
 *
 * TcpServer启动命令 php swoole.php request_uri="/Swoole/Server/TcpServer"
 * WebsocketServer启动命令 php swoole.php request_uri="/Swoole/Server/WebsocketServer"
 * HttpServer启动命令 php swoole.php request_uri="/Swoole/Server/HttpServer"
 *
 */
class ServerController extends SwooleModules
{
    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
    }

    public function TcpServerAction()
    {
        $server = new swoole_server("127.0.0.1", 9503);
        $server->on('connect', function ($server, $fd){
            echo "connection open: {$fd}\n";
            require_once("/Applications/MAMP/htdocs/phpAnalysis/agent/header.php");
        });
        $server->on('receive', function ($server, $fd, $reactor_id, $data) {
            require_once("/Applications/MAMP/htdocs/phpAnalysis/agent/header.php");
            $server->send($fd, "Swoole: {$data}");
            $server->close($fd);
        });
        $server->on('close', function ($server, $fd) {
            echo "connection close: {$fd}\n";
        });
        $server->start();
        echo "TcpServer, start, Ok!\n";
    }

    public function WebsocketServerAction()
    {
        $server = new swoole_websocket_server("127.0.0.1", 9512);

        $server->on('open', function($server, $req) {
            echo "connection open: {$req->fd}\n";
        });

        $server->on('message', function($server, $frame) {
            echo "received message: {$frame->data}\n";
            $server->push($frame->fd, json_encode(["hello", "world"]));
        });

        $server->on('close', function($server, $fd) {
            echo "connection close: {$fd}\n";
        });

        $server->start();

        echo "WebsocketServer, start, Ok!\n";
    }

    public function HttpServerAction()
    {
        $http = new swoole_http_server("127.0.0.1", 9501);

        $http->on("start", function ($server) {
            echo "Swoole http server is started at http://127.0.0.1:9501\n";
        });

        $http->on("request", function ($request, $response) {
            $response->header("Content-Type", "text/plain");
            $response->end("Hello World\n");
        });

        $http->start();

        echo "HttpServer, start, Ok!\n";
    }
}